﻿using App.Lifes;
using Microsoft.Extensions.DependencyInjection;

namespace App {
    /// <summary>
    /// DI 生命周期管理
    /// </summary>
    public static class DILifeExtension {


        /// <summary>
        /// 注册生命周期
        /// </summary>
        /// <param name="services"></param>
        /// <param name="life"></param>
        public static void RegisterLifeExtension(this IServiceCollection services)
        {
            services.RegisterLifeExtension(typeof(IScope));
            services.RegisterLifeExtension(typeof(ISingleton));
            services.RegisterLifeExtension(typeof(ITransient));
        }

        /// <summary>
        /// 注册生命周期
        /// </summary>
        /// <param name="services"></param>
        /// <param name="life"></param>
        public static void RegisterLifeExtension(this IServiceCollection services, Type lifeType)
        {
            //找到所有继承该接口的类type
            var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()).
                Where(x => lifeType.IsAssignableFrom(x) && x.IsClass && !x.IsInterface && !x.IsAbstract).ToList();

            foreach (var type in types)
            {
                var interfaces = type.GetInterfaces().Where(x => x != typeof(IScope) && x != typeof(ISingleton) && x != typeof(ITransient));

                foreach (var item in interfaces)
                {
                    if (lifeType == typeof(IScope))
                    {
                        services.AddScoped(item, type);
                    }
                    else if (lifeType == typeof(ISingleton))
                    {
                        services.AddSingleton(item, type);
                    }
                    else if (lifeType == typeof(ITransient))
                    {
                        services.AddTransient(item, type);
                    }
                }
            }

        }

    }
}
